﻿using Demo.AttachFileService.Models;
using Demo.AttachFileService.Services;
using JT808.Protocol.Extensions.JTActiveSafety.Metadata;
using JTActiveSafety.Gateway.Models;
using JTActiveSafety.Protocol;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace JTActiveSafety.Gateway.Services
{
    /// <summary>
    /// Sqlite存储方式，数据缓存到Sqlite中，完整时写入磁盘存储（也可以写入Sqlite）。
    /// </summary>
    public class SqliteAttachFileSaveService : IAttachFileStorageService
    {
        private static readonly string root = "F:\\AttachFile";

        private readonly ILogger _logger;
        private readonly ISqliteDbService _dbService;


        public SqliteAttachFileSaveService(ILoggerFactory loggerFactory, ISqliteDbService fileSaveCache)
        {
            _logger = loggerFactory.CreateLogger<SqliteAttachFileSaveService>();
            _dbService = fileSaveCache;
        }

        public Task WriteData(JTActiveSafetyPackage package)
        {
            var nodes = _dbService.WriteData(new FileRecvRecored()
            {
                FileName = package.FileName,
                Offset = package.Offset,
                Length = package.Length,
                Bodies = package.Bodies
            });

            if (nodes != null)
            {
                //var fileInfo = new AttachFileName(activeSafetyPackage.FileName);
                //if (fileInfo.IsValid)
                //{
                    SaveToFile(package.FileName, nodes, package.Offset, package.Length, package.Bodies);
                //}
            }

            return Task.CompletedTask;
        }

        private void SaveToFile(string fileName, List<FileRecvRecored> nodes, uint offset, uint length, byte[] bodies)
        {
            //_logger.LogWarning($"写入附件文件：{fileInfo.FileName} 分包-{nodes.Count + 1}");
            //return;
            try
            {
                //var path = Path.Combine(root, fileInfo.Date +"-" +fileInfo.Time + fileInfo.TerminalPhoneNo);
                ////var path = Path.Combine(root, fileInfo.Date, fileInfo.TerminalPhoneNo, fileInfo.AlarmCode + "_" + fileInfo.SN, fileInfo.Time);
                //if (!Directory.Exists(path))
                //{
                //    Directory.CreateDirectory(path);
                //}

                var fileFullName = Path.Combine(root, fileName);

                using var writer = new BinaryWriter(File.Open(fileFullName, FileMode.OpenOrCreate));
                foreach (var item in nodes)
                {
                    _logger.LogWarning($"写入附件文件{fileName} 偏移-{item.Offset} 长度-{item.Length} 结尾-{item.Offset + item.Length}");
                    writer.Seek((int)item.Offset, SeekOrigin.Begin);

                    if (item.Offset == offset && item.Length == length)
                    {
                        writer.Write(bodies);
                    }
                    else
                    {
                        var body = _dbService.ReadData(item.Id);
                        if (body != null && body.Length > 0)
                        {
                            writer.Write(body);
                            _dbService.DeleteData(item.Id);
                        }
                    }
                }
                writer.Flush();
                writer.Close();
                _dbService.HandlerEnd(fileName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "接收附件文件时写入文件出错！");
            }
            finally
            {

            }
        }
    }
}
